import axios from "axios";
import router from "@/router";
import { ElMessage } from "element-plus";

const service = axios.create({
  baseURL: import.meta.env.VUE_APP_BASE_API,
  timeout: "6000",
});

service.interceptors.request.use((config) => {
  if (config.url.indexOf("login") < 0) {
    config.headers.Authorization = `Bearer ${localStorage.getItem(
      "ats-user-token"
    )}`;
  }

  return config;
});

service.interceptors.response.use(
  (resp) => {
    const { code, data, msg } = resp.data;
    if (code == 200) {
      let result;
      if (data) {
        try {
          result = JSON.parse(data);
        } catch {
          result = data;
        }
      }
      return result;
    } else {
      ElMessage({
        message: msg,
        type: "error",
      });
      return Promise.reject(resp);
    }
  },
  (resp) => {
    const { response } = resp;
    if (response.status == 403) {
      ElMessage({
        message: response?.data?.msg || "请求失败",
        type: "warning",
      });
      localStorage.removeItem("ats-user-token");
      router.push({ path: "/login" });
    } else {
      if (
        response.data &&
        response.data.msg &&
        response.data.msg.indexOf("\r\n") > 0 &&
        response.data.msg.indexOf(":") > 0
      ) {
        response.data.msg.split("\r\n").forEach((item) => {
          ElMessage({
            message: item.split(":")[1],
            type: "error",
          });
        });
      } else {
        ElMessage({
          message: response.data.msg,
          type: "error",
        });
      }
    }
    return Promise.reject(resp);
  }
);

const request = (options) => {
  if (options.method === "get") {
    options.params = options.data;
  }

  return service(options);
};

export default request;
